package com.cardbaobao.cardbabyclient.utils;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Process;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;

import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.service.AppUpdateService;
import com.cardbaobao.cardbabyclient.ui.dialog.DownLoadDialog;
import com.cardbaobao.cardbabyclient.ui.dialog.LoadingDialog;
import com.cardbaobao.cardbabyclient.model.old.Result;
import com.cardbaobao.cardbabyclient.model.VersionInfo;
import com.umeng.analytics.MobclickAgent;

import rx.Observable;
import rx.Subscriber;

/**
 * 版本更新工具类
 * Created by zad
 * 2017/1/12 13:55
 */

public class ApkUtil {
    /**
     *  版本更新
     * @param mContext activity
     * @param isFromSetting 是否来自个人中心设置——版本更新
     */
    public static void updateVersion(final Context mContext,
                                     final boolean isFromSetting,
                                     final LoadingDialog updateDialog) {
        Observable<String> observable=
                Api.checkAppUpdate(String.valueOf(PhoneInfoUtil.getVersion(mContext)));
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {
                if (isFromSetting && updateDialog != null) {
                    updateDialog.dismiss();
                }
                VersionInfo versionInfo=JsonUtil.json2Object(s,VersionInfo.class);
                if (versionInfo != null && TextUtils.equals(versionInfo.getResult(), Result.SUCCESS)) {
                    //版本信息获取成功
                    if (PhoneInfoUtil.getVersion(mContext) < versionInfo.getVersion()) {
                        //当前版本号小于服务器版本号,执行下载
                        showDownLoadDialog(mContext, versionInfo, isFromSetting);
                    }
                    //存放当前版服务器版本号
                    SharedPreferencesUtil.CbbInfo.setAppUpdateInfo(versionInfo.getVersion(),
                            versionInfo.getApkUrl());
                }
            }
        });
    }

    /**
     *  显示是否下载提示dialog
     * @param versionInfo 服务器版本信息
     * @param isFromSetting 是否来自个人中心设置——版本更新，如果是，不能退出当前app
     */
    private static void showDownLoadDialog(final Context mContext,
                                           final VersionInfo versionInfo,
                                           final boolean isFromSetting) {
        final DownLoadDialog mDownLoadDialog = new DownLoadDialog(mContext, versionInfo.getUpdateInfo());
        mDownLoadDialog.show();
        mDownLoadDialog.setOnDownLoadClickListener(new DownLoadDialog.OnDownLoadClickListener() {
            @Override
            public void onCancel() {
                mDownLoadDialog.dismiss();
                if(versionInfo.getIsMustInstall()==1&&!isFromSetting){
                    //强制更新并且是在首页
                    exitApp(mContext);
                }
            }

            @Override
            public void onSubmit() {
                //确定,执行下载
                mDownLoadDialog.dismiss();
                if(NetUtil.isWifi(mContext)){
                    startDownloadAPK(mContext);
                }else{
                    showWarnDialog(mContext,isFromSetting);
                }
            }
        });
    }

    /**
     * 在非wifi环境下，弹出警告框，避免用户消耗过多流量
     * @param context activity
     * @param isFromSetting 是否来自
     */
    private static void showWarnDialog(final Context context,
                                       final boolean isFromSetting) {
        final AlertDialog warnDialog = new AlertDialog.Builder(context).
                setTitle("温馨提示").
                setMessage("尊敬的用户，您好，您当前处于非WIFI环境，更新APP会消耗大量流量，确定要更新吗？").
                setNegativeButton("下次更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == DialogInterface.BUTTON_NEGATIVE && !isFromSetting) {
                            //在首页时，取消更新，退出app
                            exitApp(context);
                        }
                    }
                }).
                setPositiveButton("确定更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            startDownloadAPK(context);
                        }
                    }
                }).
                setCancelable(false).
                create();
        warnDialog.show();
    }

    /**
     * 启动service，下载apk更新包
     */
    private static void startDownloadAPK(final Context context){
        Intent intent = new Intent(context, AppUpdateService.class);
        context.startService(intent);
    }

    /**
     * 退出app
     * @param activityContext activity
     */
    public static void exitApp(Context activityContext){
        if(activityContext instanceof Activity){
            MobclickAgent.onKillProcess(activityContext);//杀死进程之前，友盟统计保存数据
            ((Activity)activityContext).finish();
        }
        try{
            android.os.Process.killProcess(Process.myPid());
            System.exit(0);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
